package com.hrbxlh.virtualization.task;

import com.hrbxlh.virtualization.constant.RegistryConstant;
import com.hrbxlh.virtualization.service.DockerService;
import com.hrbxlh.virtualization.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 定时清理镜像私有仓库
 *
 * @author cheer
 */
@Component
public class RegistryGCTask {

    private Logger logger = LoggerFactory.getLogger(RegistryGCTask.class);

    private static String registryHostIp = PropertiesUtil.getProperty(
            "virtualization.properties", "docker-registry-ip");

    private static String registryName = PropertiesUtil.getProperty(
            "virtualization.properties", "docker-registry-name");

    @Autowired
    private DockerService dockerService;

    /**
     * 每天凌晨1点执行对docker镜像库进行垃圾回收
     */
    @Scheduled(cron = "0 0 1 * * *")
    public void gcRegistry() {
        logger.info("开始执行docker镜像库垃圾回收");
        try {
            dockerService.execCmd(registryHostIp, registryName, RegistryConstant.GC_CMD);
            logger.info("执行docker镜像库垃圾回收成功");
        } catch (Exception e) {
            logger.error("执行docker镜像库垃圾回收失败");
        }
    }
}
